<template>
  <div class="device-manage">
    <!-- 查询区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
      <el-form-item label="设备编号">
        <el-input v-model="searchForm.deviceId" placeholder="请输入设备编号" clearable />
      </el-form-item>
      <el-form-item label="设备名称">
        <el-input v-model="searchForm.deviceName" placeholder="请输入设备名称" clearable />
      </el-form-item>
      <el-form-item label="设备类型">
        <el-select v-model="searchForm.deviceType" placeholder="请选择设备类型" clearable>
          <el-option label="重型" value="重型" />
          <el-option label="中型" value="中型" />
          <el-option label="轻型" value="轻型" />
          <el-option label="便携式" value="便携式" />
          <el-option label="其它" value="其它" />
        </el-select>
      </el-form-item>
      <el-form-item label="出厂日期">
        <el-date-picker
          v-model="searchForm.manufactureDateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="showAddDialog = true">添加设备</el-button>
      </el-form-item>
    </el-form>

    <!-- 设备列表 -->
    <el-table :data="deviceList" border>
      <el-table-column prop="deviceId" label="设备编号" min-width="100" />
      <el-table-column prop="deviceName" label="设备名称" min-width="120" />
      <el-table-column prop="deviceType" label="设备类型" min-width="100" />
      <el-table-column prop="manufacturer" label="生产厂商" min-width="120" />
      <el-table-column prop="manufactureDate" label="出厂日期" min-width="140" :formatter="formatDate" />
      <el-table-column prop="warrantyPeriod" label="质保期" min-width="100" />
      <el-table-column prop="afterSalesContact" label="售后联系人" min-width="120" />
      <el-table-column prop="contactPhone" label="联系电话" min-width="140">
        <template #default="{ row }">{{ row.contactPhone || '-' }}</template>
      </el-table-column>
      <el-table-column label="操作" min-width="220">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEditDevice(row)">修改</el-button>
          <el-button size="small" type="danger" @click="handleDeleteDevice(row.deviceId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination

      background
      layout="prev, pager, next, jumper, ->, total"
      :total="pagination.total"
      :page-size="pagination.size"
      :current-page="pagination.current"
      @current-change="handlePageChange"
    />

    <!-- 添加设备对话框 -->
    <el-dialog :title="editDeviceId ? '修改设备' : '添加设备'" v-model="showAddDialog">
      <el-form :model="addForm" label-width="100px" :rules="formRules">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="addForm.deviceName" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="addForm.deviceType" placeholder="请选择设备类型">
            <el-option label="重型" value="重型" />
            <el-option label="中型" value="中型" />
            <el-option label="轻型" value="轻型" />
            <el-option label="便携式" value="便携式" />
            <el-option label="其它" value="其它" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产厂商" prop="manufacturer">
          <el-input v-model="addForm.manufacturer" />
        </el-form-item>
        <el-form-item label="出厂日期" prop="manufactureDate">
          <el-date-picker 
            v-model="addForm.manufactureDate" 
            type="date" 
            placeholder="选择日期" 
            value-format="YYYY-MM-DD"
            style="width: 100%;" 
          />
        </el-form-item>
        <el-form-item label="质保期" prop="warrantyPeriod">
          <el-input v-model="addForm.warrantyPeriod" />
        </el-form-item>
        <el-form-item label="售后联系人" prop="afterSalesContact">
          <el-input v-model="addForm.afterSalesContact" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="addForm.contactPhone" placeholder="请输入11位手机号" />
        </el-form-item>
        <el-form-item label="质保说明" prop="warrantyDescription">
          <el-input v-model="addForm.warrantyDescription" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false; editDeviceId = null">取消</el-button>
        <el-button type="primary" @click="handleSubmitDevice">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios';

const searchForm = reactive({
  deviceId: '',
  deviceName: '',
  deviceType: '',
  manufactureDateRange: [],
})

const addForm = reactive({
  deviceName: '',
  deviceType: '',
  manufacturer: '',
  manufactureDate: '',
  warrantyPeriod: '',
  afterSalesContact: '',
  contactPhone: '',
  warrantyDescription: ''
})

const formRules = reactive({
  deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  deviceType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  manufacturer: [{ required: true, message: '请输入生产厂商', trigger: 'blur' }],
  manufactureDate: [{ required: true, message: '请选择出厂日期', trigger: 'change' }],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

const deviceList = ref([])
const pagination = reactive({
  total: 0,
  size: 10,
  current: 1
})
const showAddDialog = ref(false)
const editDeviceId = ref<number | null>(null)

const formatDate = (row: any) => {
  return row.manufactureDate ? new Date(row.manufactureDate).toISOString().split('T')[0] : ''
}

const fetchDevices = async (pageNum = 1) => {
  try {
    const params = {
      deviceId: searchForm.deviceId || null,
      deviceName: searchForm.deviceName || null,
      deviceType: searchForm.deviceType || null,
      manufactureBeginDate: searchForm.manufactureDateRange?.[0] || null,
      manufactureEndDate: searchForm.manufactureDateRange?.[1] || null
    }
    const res = await axios.post(
      import.meta.env.VITE_API_URL + `device/page?pageNum=${pageNum}&pageSize=${pagination.size}`,
      params
    )
    deviceList.value = res.data.records
    pagination.total = res.data.total
    pagination.current = res.data.current
    pagination.size = res.data.size
  } catch (e) {
    ElMessage.error('获取设备数据失败')
  }
}

const handleEditDevice = (row: any) => {
  Object.assign(addForm, row)
  editDeviceId.value = row.deviceId
  showAddDialog.value = true
}

const handleDeleteDevice = async (deviceId: number) => {
  try {
    await axios.delete(import.meta.env.VITE_API_URL + `device/${deviceId}`)
    ElMessage.success('删除成功')
    fetchDevices(1)
  } catch (e) {
    ElMessage.error('删除失败')
  }
}

const handleSubmitDevice = async () => {
  try {
    const url = editDeviceId.value 
      ? import.meta.env.VITE_API_URL + 'device/update'
      : import.meta.env.VITE_API_URL + 'device/save'

    await axios.post(url, {
      ...addForm,
      deviceId: editDeviceId.value
    })

    ElMessage.success(editDeviceId.value ? '修改成功' : '添加成功')
    showAddDialog.value = false
    editDeviceId.value = null
    await fetchDevices(1)
  } catch (e) {
    ElMessage.error(editDeviceId.value ? '修改失败' : '添加失败')
  }
}

const handleSearch = () => fetchDevices(1)
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  })
  fetchDevices(1)
}
const handlePageChange = (page: number) => fetchDevices(page)

onMounted(() => {
  fetchDevices(1)
})
</script>

<style scoped>
@import '@/styles/views.css';
</style>